Skip to main content

Chapter 24 - Terraform CLI Workspaces with Remote Backends

Dev, Dev2, Dev3, Test1, Test2 [[TOC]]

Workspace usage


Using workspaces allows you to test and create infrastructure away from the main enviroments. The most common use for multiple workspaces is to create a parallel, distinct copy of the infrastructure instead of and before modifying the main infrastructure. NOTE: Workspaces are not recommended for multiple environments - dev, qa, staging. Use separate configuration directories instead.

A lot of times, you can replace your environment with your workspace

State file


This creates a separate state file for each of the environments:
image.png

Caveats


Code: Git 42


If you run the code as it sits, you will see that it will create businessunit-default-name infrastructure

image.png You can now create repeatable infrastructure by creating new workspaces: terraform workspace new development to get a brand new set of unique resources.

image.png

Code change:

locals {
# Use-case-1: Shorten the names for more readability
#rg_name = "${var.business_unit}-${var.environment}-${var.resoure_group_name}"
#vnet_name = "${var.business_unit}-${var.environment}-${var.virtual_network_name}"
#snet_name = "${var.business_unit}-${var.environment}-${var.subnet_name}"
#pip_name = "${var.business_unit}-${var.environment}-${var.publicip_name}"
#nic_name = "${var.business_unit}-${var.environment}-${var.network_interface_name}"
#vm_name = "${var.business_unit}-${var.environment}-${var.virtual_machine_name}"

rg_name = "${var.business_unit}-${terraform.workspace}-${var.resoure_group_name}"
vnet_name = "${var.business_unit}-${terraform.workspace}-${var.virtual_network_name}"
snet_name = "${var.business_unit}-${terraform.workspace}-${var.subnet_name}"
pip_name = "${var.business_unit}-${terraform.workspace}-${var.publicip_name}"
nic_name = "${var.business_unit}-${terraform.workspace}-${var.network_interface_name}"
vm_name = "${var.business_unit}-${terraform.workspace}-${var.virtual_machine_name}"

Example Resources:


image.png

Switching workspaces


terraform workspace list terraform workspace select development terraform workspace show

Deleting workspaces


You cannot delete the workspace when it is active:
image.png

You generally cannot delete workspaces with active resources:
image.png You can add a -force flag to remove the workspace

You cannot delete the default workspace

Adding in the remote backend